package com.example.yyg.springframework.beans.factory.support;

import com.example.yyg.springframework.beans.BeansException;
import com.example.yyg.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author: 冰岩
 * @Date: 2023/05/19
 * @Description:
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {
        Object bean = null;
        Class<?> clazz = beanDefinition.getBeanClass();
        try {
            if (ctor != null) {
                bean = clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                bean = clazz.getDeclaredConstructor().newInstance(args);
            }
            return bean;
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                 InvocationTargetException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }

}
